package com.sinodata.bsm.cicp.finder.was6;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.sinodata.bsm.cicp.finder.Finder;
import com.sinodata.bsm.cicp.util.CollectorUtil;

public class JDBCConnPoolFinder extends Finder {

    private static final Logger logger = Logger.getLogger(JDBCConnPoolFinder.class);

    @SuppressWarnings("unchecked")
    @Override
    public List<String[]> find(String ip, Map params) {
        List<String[]> list = new ArrayList<String[]>();
        try {
            String port = (String) params.get("SERVERPORT");
            String url = Util.getWasPerfToolUrl(ip, port);
            String urlStr = url + "?Module=connectionPoolModule";
            String respXml = CollectorUtil.getJmxXml(urlStr, ip, Integer.parseInt(port));
            Document doc = DocumentHelper.parseText(respXml);
            Element root = doc.getRootElement();
            List<Element> nodes = root.elements("Node");
            for (Element node : nodes) {
                String nodeName = node.attributeValue("name");
                if (nodeName.equals(params.get("NODENAME"))) {
                    List<Element> servers = node.elements("Server");
                    for (Element server : servers) {
                        String serName = server.attributeValue("name");
                        List<Element> data = server.selectNodes("Stat/Stat");
                        for (Element cp : data) {
                            String jdbcPoolName = cp.attributeValue("name");
                            if (serName.equals(params.get("SERVERNAME"))) {
                                String[] info = new String[6];
                                list.add(info);
                                info[0] = jdbcPoolName + ip;
                                info[1] = jdbcPoolName + " JDBC Connection Pool";
                                info[2] = jdbcPoolName + " JDBC Connection Pool";
                                info[3] = serName;
                                info[4] = nodeName;
                                info[5] = jdbcPoolName;
                            }
                        }
                    }
                }
            }
            return list;
        } catch (Exception e) {
            logger.error("failed to find was6 jdbcconnectionpool", e);
            return new ArrayList<String[]>();
        }
    }
}
